;(function($) {
    var index = 0,
        arrElements = [],
        timer = null,
        canSwitch = true,
        speed = 400;
    var js_header = $("#js-header"),
        container = $("#js-bg-area"),
        imgList = $("#js-bg-list");
    var listItem = imgList.find("li");

    var js_download_ios = $("#js-download-ios"); // ios版本下载按钮

    js_download_ios.on({
        "touchstart": function() {

        },
        "touchend": function() {
            window.location.href = "https://api.aizhifupay.cn/user/down";
        }
    });

    //初始化布局
    function initLayout() {
        var len = listItem.length;
        var cellWidth = (100 / len).toFixed(2) + "%";
        imgList.css('width', len * 100 + "%");
        listItem.css('width', cellWidth);
    }

    //初始化导航条
    function initPagination() {
        var len = listItem.length,
            html = "<div class='pagination'>";
        for (var i = 0; i < len; i++) {
            html += '<a href="javascript:;"></a>';
        }
        container.append(html);
        $(".pagination a:eq(0)").addClass('active');
    }

    // 切换时处理导航条激活状态
    function paginationHandler() {
        $(".pagination a").removeClass('active').eq(index).addClass('active');
    }

    // 获取元素位置
    function getElementPosition(ele) {
        var pos = ele.position();
        if (typeof pos == null) {
            return;
        }
        return pos;
    }

    function scrollPage(ele) {
        var pos = getElementPosition(ele);
        var left = pos.left;
        if (index === 1) {
            js_header.addClass("header-download");
        } else {
            js_header.removeClass("header-download");
        }
        imgList.animate({ "left": -left }, speed, function() {
            canSwitch = true;
        });
        paginationHandler();
    }

    function autoPlay() {
        timer = setInterval(function() {
            index++;
            if (index >= listItem.length) {
                index = 0;
            }
            scrollPage(arrElements[index]);
        }, 5000);
    }

    function clickable() {
        $(".pagination a").on("click", function() {
            if (canSwitch) {
                canSwitch = false;
                index = $(this).index();
                scrollPage(arrElements[index]);
            }
        });
    }

    function switchPage() {
        listItem.each(function() {
            arrElements.push($(this));
        });

        initLayout();
        initPagination();
        autoPlay();
        clickable();
    }

    switchPage();
})(jQuery);